package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.WireCuttingRecordMapper;
import com.yupi.springbootinit.model.dto.wirecutting.WireCuttingRecordAddRequest;
import com.yupi.springbootinit.model.dto.wirecutting.WireCuttingRecordQueryRequest;
import com.yupi.springbootinit.model.dto.wirecutting.WireCuttingRecordUpdateRequest;
import com.yupi.springbootinit.model.entity.WireCuttingRecord;
import com.yupi.springbootinit.model.vo.WireCuttingRecordVO;
import com.yupi.springbootinit.service.ProcessSheetService;
import com.yupi.springbootinit.service.WireCuttingRecordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 线切割记录服务实现
 */
@Service
@Slf4j
public class WireCuttingRecordServiceImpl extends ServiceImpl<WireCuttingRecordMapper, WireCuttingRecord>
        implements WireCuttingRecordService {

    @Resource
    private ProcessSheetService processSheetService;

    @Override
    public Long addRecord(WireCuttingRecordAddRequest addRequest) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        // 参数校验
        validateAddParams(addRequest);

        WireCuttingRecord record = new WireCuttingRecord();
        BeanUtils.copyProperties(addRequest, record);

        // 如果没有指定工艺单号和规格型号，根据产品名称自动查询
        if (StringUtils.isNotBlank(addRequest.getProductName()) &&
                (StringUtils.isBlank(addRequest.getProcessSheetNo()) || StringUtils.isBlank(addRequest.getSpecification()))) {
            Map<String, Object> processSheetInfo = processSheetService.queryProcessSheetByProductName(addRequest.getProductName());

            if (StringUtils.isBlank(addRequest.getProcessSheetNo())) {
                record.setProcessSheetNo((String) processSheetInfo.get("processSheetNo"));
            }

            // 从工艺单中获取规格型号（假设ProcessSheet实体中有specification字段）
            // 这里需要根据实际的ProcessSheet结构调整
            if (StringUtils.isBlank(addRequest.getSpecification())) {
                // 可能需要额外查询获取规格型号
                record.setSpecification((String) processSheetInfo.get("specification"));
            }
        }

        boolean result = this.save(record);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加记录失败");
        }

        return record.getId();
    }

    @Override
    public Boolean updateRecord(WireCuttingRecordUpdateRequest updateDTO) {
        if (updateDTO == null || updateDTO.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }

        // 检查记录是否存在
        WireCuttingRecord oldRecord = this.getById(updateDTO.getId());
        if (oldRecord == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "记录不存在");
        }

        WireCuttingRecord record = new WireCuttingRecord();
        BeanUtils.copyProperties(updateDTO, record);

        boolean result = this.updateById(record);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新记录失败");
        }

        return true;
    }

    @Override
    public Boolean deleteRecord(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "记录ID错误");
        }

        // 检查记录是否存在
        WireCuttingRecord record = this.getById(id);
        if (record == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "记录不存在");
        }

        boolean result = this.removeById(id);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除记录失败");
        }

        return true;
    }

    @Override
    public WireCuttingRecordVO getRecordById(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "记录ID错误");
        }

        WireCuttingRecord record = this.getById(id);
        if (record == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "记录不存在");
        }

        return entityToVO(record);
    }

    @Override
    public Page<WireCuttingRecordVO> pageRecords(WireCuttingRecordQueryRequest queryDTO) {
        if (queryDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询参数为空");
        }

        int current = queryDTO.getCurrent();
        int pageSize = queryDTO.getPageSize();

        // 构建查询条件
        QueryWrapper<WireCuttingRecord> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(queryDTO.getProcessSheetNo())) {
            queryWrapper.eq("process_sheet_no", queryDTO.getProcessSheetNo());
        }
        if (StringUtils.isNotBlank(queryDTO.getMachineNo())) {
            queryWrapper.eq("machine_no", queryDTO.getMachineNo());
        }
        if (StringUtils.isNotBlank(queryDTO.getProductName())) {
            queryWrapper.like("product_name", queryDTO.getProductName());
        }
        if (StringUtils.isNotBlank(queryDTO.getOperator())) {
            queryWrapper.like("operator", queryDTO.getOperator());
        }
        if (queryDTO.getStartDate() != null) {
            queryWrapper.ge("usage_date", queryDTO.getStartDate());
        }
        if (queryDTO.getEndDate() != null) {
            queryWrapper.le("usage_date", queryDTO.getEndDate());
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");

        // 分页查询
        Page<WireCuttingRecord> page = this.page(new Page<>(current, pageSize), queryWrapper);

        // 转换为VO
        Page<WireCuttingRecordVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(page.getRecords().stream().map(this::entityToVO).collect(java.util.stream.Collectors.toList()));

        return voPage;
    }

    /**
     * 实体转VO
     */
    private WireCuttingRecordVO entityToVO(WireCuttingRecord record) {
        if (record == null) {
            return null;
        }
        WireCuttingRecordVO vo = new WireCuttingRecordVO();
        BeanUtils.copyProperties(record, vo);
        return vo;
    }

    /**
     * 参数校验
     */
    private void validateAddParams(WireCuttingRecordAddRequest addDTO) {
        if (addDTO.getUsageDate() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "使用日期不能为空");
        }
        if (StringUtils.isBlank(addDTO.getProductName())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "产品名称不能为空");
        }
        if (StringUtils.isBlank(addDTO.getMachineNo())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "机台号不能为空");
        }
        if (addDTO.getStartTime() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始时间不能为空");
        }
        if (StringUtils.isBlank(addDTO.getOperator())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "操作人不能为空");
        }
    }
}